package com.basic.common.area;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.basic.common.constant.CommonDsConstant;
import com.basic.common.http.HttpClientDsUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 
 * @explain
 * @since 2017/11/27 9:28
 */
public class IpDsUtil {

    private static Logger log = LoggerFactory.getLogger(IpDsUtil.class);
    private static final String BAIDU_AK = "5c17eea993bd1bbf6d5a16aab3882e3b";

    public static String getIp() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    // 判断是否是IPv4地址，并且不是环回地址（127.0.0.1）
                    if (ip instanceof Inet4Address && !ip.isLoopbackAddress()) {
                        return ip.getHostAddress(); // 返回找到的第一个非环回IPv4地址
                    }
                }
            }
        } catch (SocketException e) {
            log.error("Get IP Exception: {}", e.getMessage());
        }
        return "Unknown IP"; // 返回一个默认值而不是空字符串
    }

    public static String getIp(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                ip = ip.substring(0, index);
            }
        } else {
            ip = Xip;
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        }
        return ip;
    }

    public static AreaResDsBean getAreaFromBaidu(String ip) {
        try {
            if (null == ip || "".equals(ip)) {
                return null;
            }
            String urlStr = "http://api.map.baidu.com/location/ip?ak=" + BAIDU_AK + "&ip=" + ip;
            String str = HttpClientDsUtil.doGet(urlStr);
            JSONObject jsonObject = JSON.parseObject(str);
            JSONObject jsonContent = jsonObject.getJSONObject("content");
            if (null == jsonContent) {
                return null;
            }
            AreaResDsBean areaResDsBean = new AreaResDsBean();

            JSONObject terminalJson = jsonObject.getJSONObject("content").getJSONObject("address_detail");

            String provinceName = terminalJson.getString("province");
            areaResDsBean.setProvince(provinceName);

            String cityName = terminalJson.getString("city");
            areaResDsBean.setCity(cityName);

            String district = terminalJson.getString("district");
            areaResDsBean.setDistrict(district);

            String adcode = terminalJson.getString("adcode");
            areaResDsBean.setAdcode(adcode);
            return areaResDsBean;
        } catch (Exception e) {
            log.error("根据IP获取地址错误！(baidu)" + e.getMessage());
        }
        return null;
    }

    public static Map<String, String> getFullNameFromBaidu(String ip) {
        try {
            if (null == ip || "".equals(ip)) {
                return null;
            }
            Map<String, String> resulet = new HashMap<>(16);
            if (ip.split(CommonDsConstant.DELIMITER_DH).length > 1) {
                ip = ip.split(CommonDsConstant.DELIMITER_DH)[0];
            }
            String urlStr = "http://api.map.baidu.com/location/ip?ak=" + BAIDU_AK + "&ip="
                    + ip;
            String str = HttpClientDsUtil.doGet(urlStr);
            JSONObject jsonObject = JSON.parseObject(str);
            JSONObject jsonContent = jsonObject.getJSONObject("content");
            if (null == jsonContent) {
                return null;
            }
            JSONObject terminalJson = jsonObject.getJSONObject("content").getJSONObject("address_detail");

            String provinceName = terminalJson.getString("province");
            resulet.put(AliMapDsConstant.NODE_NAME_PROV, provinceName);
            String cityName = terminalJson.getString("city");
            resulet.put(AliMapDsConstant.NODE_NAME_CITE, cityName);
            return resulet;
        } catch (Exception e) {
            log.error("根据IP获取地址错误！(baidu)" + e.getMessage());
        }
        return null;
    }

    public static String getAreaFullName(String ip) {
        Map<String, String> result = getFullNameFromBaidu(ip);
        if (result == null) {
            return null;
        }
        String fullName = result.get(AliMapDsConstant.NODE_NAME_PROV);
        String city = result.get(AliMapDsConstant.NODE_NAME_CITE);
        if (StringUtils.isNoneEmpty(city)) {
            fullName += "/" + city;
        }
        return fullName;
    }

}
